package com.jkoss.wine.system.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jkoss.base.controller.BaseController;
import com.jkoss.common.util.CommonUtil;
import com.jkoss.common.vo.DwzPageBean;
import com.jkoss.common.vo.ZtreeBean;
import com.jkoss.wine.system.entity.Department;
import com.jkoss.wine.system.entity.Permission;
import com.jkoss.wine.system.entity.Role;
import com.jkoss.wine.system.service.ICommonlyService;
import com.jkoss.wine.system.service.IDepartmentService;
import com.jkoss.wine.system.service.IPermissionService;
import com.jkoss.wine.system.service.IRolePermissionService;
import com.jkoss.wine.system.service.IRoleService;

/**
 * <p>
 * 角色 前端控制器
 * </p>
 *
 * @author chair
 * @since 2018-09-20
 */
@Controller
@RequestMapping("/system/role")
public class RoleController extends BaseController {

	@Autowired
	private IRoleService iRoleService;
	@Autowired
	private IRolePermissionService iRolePermissionService;
	@Autowired
	private IPermissionService iPermissionService;
	@Autowired
	private ICommonlyService iCommonlyService;
	@Autowired
	private IDepartmentService iDepartmentService;

	/**
	 * 列表
	 * 
	 * @param roleName
	 * @param dwzPageBean
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/list")
	@RequiresPermissions("/system/role/list")
	public String list(String roleName, DwzPageBean dwzPageBean, ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		dwzPageBean.getCountResultMap().put("roleName", roleName);
		Wrapper wrapper = Condition.create().ne("r.del", 1).like("r.name", roleName);

		// 字段排序
		if (!CommonUtil.isBlank(dwzPageBean.getOrderField()) && !CommonUtil.isBlank(dwzPageBean.getOrderDirection())) {
			dwzPageBean.getCountResultMap().put("orderField", dwzPageBean.getOrderField());
			dwzPageBean.getCountResultMap().put("orderDirection", dwzPageBean.getOrderDirection());
			wrapper.orderBy(dwzPageBean.getOrderField(), CommonUtil.isEquals(dwzPageBean.getOrderDirection(), "asc"));
		}
		Page resultPage = iRoleService.selectVoByPage(dwzPageBean.toPage(), wrapper);
		map.put("dwzPageBean", dwzPageBean.toDwzPageBean(resultPage));
		return "system/role/list";
	}

	/**
	 * 去新增
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/toInsert")
	@RequiresPermissions("/system/role/toInsert")
	public String toInsert(ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		// 岗位-角色
		Wrapper wrapper = Condition.create().ne("del", 1);
		List<Role> roles = iRoleService.selectList(wrapper);
		map.put("roles", roles);
		// 部门
		Wrapper dmWrapper = Condition.create().ne("del", 1);
		List<Department> departments = iDepartmentService.selectList(dmWrapper);
		map.put("departments", departments);
		return "system/role/edit";
	}

	@RequestMapping("/insert")
	@RequiresPermissions("/system/role/toInsert")
	@ResponseBody
	public Object insert(@Valid Role role, HttpServletRequest request, HttpServletResponse response) {
		role.setDel(0);
		if (iRoleService.insert(role)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}

	}

	/**
	 * 去修改
	 * 
	 * @param id
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/toUpdate")
	@RequiresPermissions("/system/role/toUpdate")
	public String toUpdate(String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		map.put("record", iRoleService.selectById(id));
		Wrapper wrapper = Condition.create().ne("del", 1);
		List<Role> roles = iRoleService.selectList(wrapper);
		map.put("roles", roles);
		// 部门
		Wrapper dmWrapper = Condition.create().ne("del", 1);
		List<Department> departments = iDepartmentService.selectList(dmWrapper);
		map.put("departments", departments);
		return "system/role/edit";
	}

	@RequestMapping("/update")
	@RequiresPermissions("/system/role/toUpdate")
	@ResponseBody
	public Object update(@Valid Role role, HttpServletRequest request, HttpServletResponse response) {
		if (iRoleService.updateById(role)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	/**
	 * 去删除
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("/system/role/delete")
	@ResponseBody
	public Object delete(String[] id, HttpServletRequest request, HttpServletResponse response) {
		List list = new ArrayList();
		for (String string : id) {
			Role role = new Role();
			role.setId(string);
			// 是否删除：0-未删除、1-已删除、2-不能删除
			role.setDel(1);
			list.add(role);
		}
		if (iRoleService.updateBatchById(list)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	/**
	 * 去权限
	 * 
	 * @param id
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toUpdatePermission")
	@RequiresPermissions("/system/role/toUpdatePermission")
	public String toUpdatePermission(String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 把要权限的角色ID传递到页面去
		map.put("id", id);
		// 查询该角色得权限
		List<String> pids = iRolePermissionService.selectPidByRid(id);
		// 查询所有权限
		Wrapper wrapper = Condition.create().ne("del", 1).orderBy("level", true).orderBy("sort", true);
		List<Permission> permissions = iPermissionService.selectList(wrapper);
		// 把查询回来的实体转成ZtreeBean
		if (!CommonUtil.isBlank(permissions)) {
			List<ZtreeBean> ztreeBeans = new ArrayList();
			for (Permission permission : permissions) {
				ZtreeBean ztreeBean = new ZtreeBean();
				ztreeBean.setId(permission.getId() + "");
				ztreeBean.setIsParent(CommonUtil.isBlank(permission.getPid()));
				ztreeBean.setName(permission.getName());
				ztreeBean.setPId(permission.getPid());
				ztreeBean.setOpen(true);
				// 匹配该权限是否已经选中
				ztreeBean.setChecked(pids.contains(permission.getId()));
				ztreeBeans.add(ztreeBean);
			}
			map.put("ztreeBeans", JSON.toJSONString(ztreeBeans));
		} else {
			map.put("ztreeBeans", "[]");
		}

		return "system/role/updatePermission";
	}

	@RequestMapping("/updatePermission")
	@RequiresPermissions("/system/role/toUpdatePermission")
	@ResponseBody
	public Object updateTpPermission(String id, String[] pid, ModelMap map, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (iRolePermissionService.updatePermission(id, pid)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	/**
	 * 去权限角色
	 * 
	 * @param id
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toUpdateCommonly")
	@RequiresPermissions("/system/role/toUpdateCommonly")
	public String toUpdateCommonly(String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 把要权限的角色ID传递到页面去
		map.put("id", id);
		// 查询该角色得权限
		List<String> commonlies = iCommonlyService.selectPidByRid(id);
		// 查询所有权限
		Wrapper wrapper = Condition.create().ne("del", 1).ne("type", 2).orderBy("level", true).orderBy("sort", true);
		List<Permission> permissions = iPermissionService.selectList(wrapper);
		// 把查询回来的实体转成ZtreeBean
		if (!CommonUtil.isBlank(permissions)) {
			List<ZtreeBean> ztreeBeans = new ArrayList();
			for (Permission permission : permissions) {
				ZtreeBean ztreeBean = new ZtreeBean();
				ztreeBean.setId(permission.getId() + "");
				ztreeBean.setIsParent(CommonUtil.isBlank(permission.getPid()));
				ztreeBean.setName(permission.getName());
				ztreeBean.setPId(permission.getPid());
				ztreeBean.setOpen(true);
				// 匹配该权限是否已经选中
				ztreeBean.setChecked(commonlies.contains(permission.getId()));
				if (permission.getType() == 0) {
					ztreeBean.setNocheck(true);
				}
				ztreeBeans.add(ztreeBean);
			}
			map.put("ztreeBeans", JSON.toJSONString(ztreeBeans));
		} else {
			map.put("ztreeBeans", "[]");
		}

		return "system/role/updateCommonly";
	}

	@RequestMapping("/updateCommonly")
	@RequiresPermissions("/system/role/toUpdateCommonly")
	@ResponseBody
	public Object updateCommonly(String id, String[] pid, ModelMap map, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (iCommonlyService.updateCommonly(id, pid)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}
}
